package com.yixin.hospital.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.domain.VisitTemplate;
import com.yixin.hospital.entity.dto.req.visitTemplate.VisitTemplateAddReqDTO;
import com.yixin.hospital.entity.dto.req.visitTemplate.VisitTemplateEditReqDTO;
import com.yixin.hospital.entity.dto.req.visitTemplate.VisitTemplateEditTemplateReqDTO;
import com.yixin.hospital.entity.vo.VisitTemplateVO;
import com.yixin.hospital.service.JobOfficeService;
import com.yixin.hospital.service.VisitTemplateJobOfficeService;
import com.yixin.hospital.service.VisitTemplateService;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/visit-template")
@Api(value = "就诊模板管理", tags = "就诊模板管理")
public class VisitTemplateController {

    @Resource
    VisitTemplateService visitTemplateService;


    @GetMapping("/list")
    @ApiOperation(value = "就诊模板列表（树状）")
    public ApiResult list(String templateCode) {
        List<VisitTemplate> visitTemplateList = visitTemplateService.list(new LambdaUpdateWrapper<VisitTemplate>().eq(VisitTemplate::getTemplateCode, templateCode));
        List<VisitTemplateVO> visitTemplateVOList = BeanUtil.copyToList(visitTemplateList, VisitTemplateVO.class);
        TreeNodeConfig nodeConfig = new TreeNodeConfig();
        List<Tree<Integer>> treeList = TreeUtil.build(visitTemplateVOList, 0, nodeConfig,
                (node, tree) -> {
                    tree.setId(node.getId().intValue());
                    tree.setParentId(node.getPid().intValue());
                    tree.setName(node.getName());
                    tree.putExtra("level", node.getLevel());
                    tree.putExtra("sort", node.getSort());
                    tree.putExtra("templateCode", node.getTemplateCode());
                    tree.putExtra("templateName", node.getTemplateName());
                });
        if (CollectionUtil.isEmpty(treeList)) return ApiResult.success(new ArrayList<>());
        for (Tree<Integer> integerTree : treeList) {
            getChildren(integerTree);
        }
        treeList.sort(Comparator.comparing(o -> Integer.valueOf((int) o.get("sort"))));
        return ApiResult.success(treeList);
    }

    private List<Tree<Integer>> getChildren(Tree<Integer> integerTree) {
        if (!CollectionUtil.isEmpty(integerTree.getChildren())) {
            integerTree.getChildren().sort(Comparator.comparing(o -> Integer.valueOf((int) o.get("sort"))));
            for (Tree<Integer> child : integerTree.getChildren()) {
                getChildren(child);
            }
        }
        return null;
    }

    @PostMapping("/add")
    @ApiOperation(value = "新增就诊管理类别")
    public ApiResult add(@Valid @RequestBody VisitTemplateAddReqDTO visitTemplateAddReqDTO, HttpServletRequest request) {
        VisitTemplate visitTemplate = new VisitTemplate();
        BeanUtil.copyProperties(visitTemplateAddReqDTO, visitTemplate);
        visitTemplate.setTemplateCode(StringUtils.isBlank(visitTemplateAddReqDTO.getTemplateCode()) ? String.valueOf(System.currentTimeMillis()) : visitTemplateAddReqDTO.getTemplateCode());
        visitTemplate.setPid(visitTemplateAddReqDTO.getParentId());
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        visitTemplate.setCreatedBy(userName);
        visitTemplate.setUpdatedBy(userName);
        visitTemplateService.save(visitTemplate);

        VisitTemplate updateVisitTemplate = new VisitTemplate();
        updateVisitTemplate.setTemplateName(visitTemplateAddReqDTO.getTemplateName());
        LambdaUpdateWrapper<VisitTemplate> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(VisitTemplate::getTemplateCode, visitTemplateAddReqDTO.getTemplateCode());
        visitTemplateService.update(updateVisitTemplate, updateWrapper);
        return ApiResult.success(visitTemplate);
    }

    @PutMapping("/edit")
    @ApiOperation(value = "修改就诊管理类别")
    public ApiResult edit(@Valid @RequestBody VisitTemplateEditReqDTO visitTemplateEditReqDTO, HttpServletRequest request) {
        VisitTemplate visitTemplate = new VisitTemplate();
        BeanUtil.copyProperties(visitTemplateEditReqDTO, visitTemplate);
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        visitTemplate.setUpdatedBy(userName);
        visitTemplateService.updateById(visitTemplate);

        VisitTemplate updateVisitTemplate = new VisitTemplate();
        updateVisitTemplate.setTemplateName(visitTemplateEditReqDTO.getTemplateName());
        LambdaUpdateWrapper<VisitTemplate> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(VisitTemplate::getTemplateCode, visitTemplateEditReqDTO.getTemplateCode());
        visitTemplateService.update(updateVisitTemplate, updateWrapper);
        return ApiResult.success(visitTemplate);
    }

    @PutMapping("/edit-templateName")
    @ApiOperation(value = "修改模板名称")
    public ApiResult editTemplateName(@Valid @RequestBody VisitTemplateEditTemplateReqDTO visitTemplateEditReqDTO, HttpServletRequest request) {
        VisitTemplate visitTemplate = new VisitTemplate();
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        visitTemplate.setUpdatedBy(userName);
        visitTemplate.setTemplateName(visitTemplateEditReqDTO.getTemplateName());
        LambdaUpdateWrapper<VisitTemplate> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(VisitTemplate::getTemplateCode, visitTemplateEditReqDTO.getTemplateCode());
        visitTemplateService.update(visitTemplate, updateWrapper);
        return ApiResult.success();
    }

    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "删除就诊管理类别")
    public ApiResult remove(@PathVariable int id) {
        visitTemplateService.removeById(id);
        return ApiResult.success();
    }

    @GetMapping("/template-list")
    @ApiOperation(value = "就诊模板列表")
    public ApiResult templateList() {
        List<VisitTemplate> list = visitTemplateService.list(new LambdaUpdateWrapper<VisitTemplate>().groupBy(VisitTemplate::getTemplateCode));
        return ApiResult.success(list);
    }

}
